package com.powernode.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.powernode.config.WhiteUrlsConfig;
import com.powernode.constant.AuthConstants;
import com.powernode.constant.BusinessEnum;
import com.powernode.model.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Date;

/**
 * @description:
 * @author: mky
 * @date: 2024/7/4 14:04
 * @version: 1.0
 */
@Component
@Slf4j
public class AuthFilter implements GlobalFilter,Ordered{
    @Autowired
    private WhiteUrlsConfig whiteUrlsConfig;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String authorization = request.getHeaders().getFirst(AuthConstants.AUTHORIZATION);
        String path = request.getPath().toString();
        //判断白名单有没有这个路径
        if (whiteUrlsConfig.getAllowUrls().contains(path)){
            return chain.filter(exchange);
        }
         if (StringUtils.hasText(authorization)){
            String token = authorization.replace(AuthConstants.TOKEN_PREFIX, "");
            if (StringUtils.hasText(token) && redisTemplate.hasKey(token)){
                return chain.filter(exchange);
            }
        }
        //失败，不能放行
        log.error("拦截非法请求，拦截时间:{}，请求api接口:{}",new Date(),path);
        ServerHttpResponse response = exchange.getResponse();
        response.getHeaders().set(AuthConstants.CONTENT_TYPE,AuthConstants.APPLICATION_JSON);
        Result result = Result.failure(BusinessEnum.UN_AUTHORIZATION);
        ObjectMapper objectMapper = new ObjectMapper();
        byte[] bytes;
        try {
            bytes = objectMapper.writeValueAsBytes(result);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        DataBuffer dataBuffer = response.bufferFactory().wrap(bytes);
        return response.writeWith(Mono.just(dataBuffer));
    }

    @Override
    public int getOrder() {
        return -1;
    }
}
